<template>
    <ul class="directory-tree">
        <child-page ref="addChild"></child-page>
        <edit-page ref="Edit"></edit-page>

        <li v-for="(item, index) in menu" :key="index">
            <div class="item-container" :class="{ 'type-normal': !showEdit }">
                <i class="folder-icon" :class="{ open: item.id === currentExpandedId }"></i>
                <span class="item-name" :class="{
                    'edit-mode': showEdit,
                    selected: item.id === currentExpandedId,
                }" @click.stop="toggleExpand(item)">{{ item.name }}</span>



                <div class="item-actions" v-if="showEdit">
                    <div class="item-actions__switch">
                        <el-button size="mini" type="success" @click="handleNewSubfolder(item)">添加子栏目</el-button>
                        <el-button size="mini" type="info"  @click="handleEdit(item)">修改栏目名称</el-button>
                        <el-button size="mini" type="danger"  @click="handleDelete(item)">删除栏目</el-button>

                        <div class="order">
                            <el-button size="mini" icon="el-icon-top" @click="setPrevOrder(item)"
                                v-if="index !== 0">上移</el-button>
                            <el-button size="mini" icon="el-icon-bottom" @click="setNextOrder(item)"
                                v-if="index + 1 < menu.length">下移</el-button>
                        </div>

                        <el-switch v-if="item.level < 3" :value="!!item.status" :width="32"
                            @change="handleChangeStatus(item)" active-text="官网显示">
                        </el-switch>

                        <span class="creator">创建人  : {{ item.creator }}</span>
                    </div>
                </div>
            </div>
            <!-- 递归地渲染子菜单，并传递当前项的展开状态 -->

            <menu-item v-if="findDescendantById(item.children, currentExpandedId) ||
                item.id === currentExpandedId
                " :menu="item.children" :showEdit="showEdit" :currentExpandedId="currentExpandedId" />
        </li>
    </ul>
</template>

<script>
import ChildPage from "./ChildPage.vue";
import EditPage from "./EditPage.vue";
import { EventBus } from "@/EventBus"; // 假设EventBus.js位于src目录下

export default {
    name: "menuItem",
    components: {
        ChildPage,
        EditPage,
    },
    props: {
        showEdit: {
            default: false,
        },
        menu: {
            type: Array,
            required: true,
        },
        currentExpandedId: {
            type: Number,
            default: null,
        },
        selectedItemId: {
            type: Number,
            default: null,
        },
    },

    methods: {
        handleEdit(item) {
            return this.$refs.Edit && this.$refs.Edit.visible(item);
        },
        async handleDelete(item) {
            this.$confirm("确定要删除此栏目嘛，删除后后能影响展示，请慎重", "", {
                distinguishCancelAndClose: true,
                confirmButtonText: "确认",
                cancelButtonText: "取消",
            })
                .then(async () => {
                    const { code } = await this.$fetch.post("/api/directory/delete", {
                        id: item.id,
                    });
                    if (code === 0) {
                        EventBus.$emit("menuRefresh");
                        this.$message.success("成功");
                    }
                })
                .catch(() => { });
        },

        async setPrevOrder(item) {
            const { code } = await this.$fetch.post("/api/directory/setPrevOrder", {
                id: item.id,
            });
            if (code === 0) {
                EventBus.$emit("menuRefresh");
                this.$message.success("成功");
            }
        },
        async setNextOrder(item) {
            const { code } = await this.$fetch.post("/api/directory/setNextOrder", {
                id: item.id,
            });
            if (code === 0) {
                EventBus.$emit("menuRefresh");
                this.$message.success("成功");
            }
        },
        handleNewSubfolder(item) {
            return this.$refs.addChild && this.$refs.addChild.visible(item.id);
        },
        toggleExpand(item) {
            EventBus.$emit("expandItem", item.id);
        },

        async handleChangeStatus(item) {
            const status = item.status === 0 ? 1 : 0;
            const { code } = await this.$fetch.post("/api/directory/updateStatus", {
                id: item.id,
                status: item.status === 0 ? 1 : 0,
            });
            if (code === 0) {
                EventBus.$emit("menuRefresh");
                this.$message.success(`该栏目${status ? "开启" : "关闭"}`);
            }
        },

        /* eslint-disable */
        findDescendantById(menu, targetId) {
            for (const item of menu) {
                if (item.id === targetId) {
                    return item;
                }

                if (item.children && item.children.length > 0) {
                    const descendant = this.findDescendantById(item.children, targetId);
                    if (descendant) {
                        return descendant;
                    }
                }
            }

            return null;
        },
    },
};
</script>

<style scoped lang="scss">
::v-deep .el-switch__label {
    font-size: 12px;
    margin-right: 4px;
}

.directory-tree {
    list-style-type: none;
    padding-left: 32px;
    margin: 0;
}

.item-container {
    display: flex;
    align-items: center;
    user-select: none;

    &.type-normal {
        min-height: 36px;
    }
}

.folder-icon {
    display: inline-block;
    width: 16px;
    height: 16px;
    margin-right: 8px;
    background-image: url("../assets/folder.svg");
    background-size: contain;
    background-repeat: no-repeat;
    transition: transform 0.2s ease-in-out;
}

.folder-icon.open {
    transform: rotate(180deg);
}

.item-name {
    cursor: pointer;
    margin-right: 16px;
    /* 减少与actions的间距 */
    font-size: 12px;
    max-width: 168px;
    overflow-wrap: break-word;

    &.edit-mode {
        max-width: max-content;
    }
}

.item-actions {
    display: flex;
    align-items: center;
    margin-left: auto;
    height: 40px;
    margin-left: 10px;

    .item-actions__switch {
        margin-right: 12px;
    }

    .creator {
        font-size: 12px;
        padding: 0 4px;
        color: #999;
    }

    .order {
        display: inline-flex;
        flex-direction: row;
        justify-content: space-between;
        margin-right: 10px;
        align-items: center;
    }
}

.item-actions button {
    margin-right: 4px;
    margin-left: 4px;

}

.selected {
    color: #ff5722; // 或者您选择的高亮颜色
    font-weight: bold; // 可选，增加字体加粗效果
}
</style>
